/**
 *
 */
package com.honeybees.web.captcha.patchca.background;

import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.image.BufferedImage;
import java.util.Random;

import org.patchca.background.BackgroundFactory;
import org.springframework.stereotype.Component;

/**
 * <dl>
 * <dt><b> 标题 </b></dt>
 * <p>
 * <dd>功能描述</dd>
 * </dl>
 * <p>
 * Copyright (C) All rights reserved.
 * </p>
 *
 * @author 李远明
 * @version 2016年5月27日 上午11:02:45
 */
@Component
public class NoLineBackgroundFactory implements BackgroundFactory {

    private Random random = new Random();

    /**
     * {@inheritDoc}
     *
     * @author 李远明
     * @version 2016年5月27日 上午11:02:45
     */
    @Override
    public void fillBackground(BufferedImage dest) {
        Graphics graphics = dest.getGraphics();

        int imgWidth = dest.getWidth();
        int imgHeight = dest.getHeight();

        Graphics2D g2 = (Graphics2D) graphics;
        Paint storedPaint = g2.getPaint();

        boolean flag = random.nextBoolean();
        if (random.nextBoolean()) {
            g2.setPaint(new GradientPaint(flag ? 0.0F : imgWidth, 0.0F, getRandomColor(), flag ? imgWidth : 0.0F,
                    imgHeight, Color.WHITE));
        } else {
            g2.setPaint(new GradientPaint(flag ? 0.0F : imgWidth, 0.0F, Color.WHITE, flag ? imgWidth : 0.0F, imgHeight,
                    getRandomColor()));
        }
        g2.fillRect(0, 0, imgWidth, imgHeight);
        g2.setPaint(storedPaint);

        for (int i = 0; i < 60; i++) {
            graphics.setColor(getRandomColor());

            int x1 = random.nextInt(imgWidth - 3);
            int y1 = random.nextInt(imgHeight - 2);

            int width = random.nextInt(6);
            int height = random.nextInt(6);

            int startAngle = random.nextInt(360);
            int arcAngle = random.nextInt(360);

            graphics.fillArc(x1, y1, width, height, startAngle, arcAngle);
        }
    }

    Color getRandomColor() {
        int r = random.nextInt(255);
        int g = random.nextInt(255);
        int b = random.nextInt(255);
        return new Color(r, g, b);
    }
}
